#include "AccountHandler.h"
#include "boost/bind.hpp"
#include "MysqlConnector.h"
#include "RPC_account.pb.h"
#include "AccountServer.h"

const static int MAX_SQL_LENGTH = 256;

#ifdef WIN32
#define DBSPRINT sprintf_s
#else
#define DBSPRINT sprintf
#endif // WIN32
void AccountRpcHandler::init()
{
	regRpcHandler("requestLogin", boost::bind(&AccountRpcHandler::remote_requesetLogin, this, _1));
}

string AccountRpcHandler::remote_requesetLogin( const string& params )
{
	RPC_RequestLoginRes pres;
	pres.set_res(RPC_RequestLoginRes_LoginState_Unkown);

	return pres.SerializeAsString();

	try
	{
		RPC_RequestLogin p;
		p.ParseFromString(params);

		MysqlConnHelper mysqlconn(AccountServer::getInstance()->getDBPool());
		char sql[MAX_SQL_LENGTH];

		DBSPRINT( sql, "select password from account_db where username='%s'", p.name().c_str());
		if (!mysqlconn->query(sql))
		{
			pres.set_res(RPC_RequestLoginRes_LoginState_Unkown);
		}
		else if( mysqlconn->isResEmpty() ) // No username found
		{
			pres.set_res(RPC_RequestLoginRes_LoginState_NotFound);
		}
		else
		{
			MYSQL_RES* res = mysqlconn->getRes();
			MYSQL_ROW row = mysql_fetch_row( res );

			if( row )
			{
				string pwd = row[0];
				if ( pwd.compare(p.pwd()) )
				{
					pres.set_res(RPC_RequestLoginRes_LoginState_PasswordError);
				}
				else
				{
					pres.set_res(RPC_RequestLoginRes_LoginState_Succeed);
				}
			}
		}
	}
	catch (const char* e)
	{
		LogE << e << LogEnd;
	}
	return pres.SerializeAsString();
}
